package AwsSES;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.MessageRejectedException;
import com.amazonaws.services.simpleemail.model.RawMessage;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
import com.amazonaws.services.simpleemail.model.SendRawEmailResult;
import com.amazonaws.services.simpleworkflow.flow.TimerException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

public class RawMessageExemple {

    public static final String ACCESS_KEY = "AKIAJICRH6ZVS7ENHQMA";
    public static final String SECRET_KEY = "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";
    public static final long TAMANHO_LIMITE_MSG = 10485760;

    public static void main(String[] args) throws MessagingException, IOException {

        AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "aws");
        props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
        props.setProperty("mail.aws.password", credentials.getAWSSecretKey());

        Session session = Session.getInstance(props);

        //MONTAGEM DA MENSAGEM
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("bsmrio@gmail.com"));
        msg.addRecipients(Message.RecipientType.TO, "bruno.maria@delphos.com.br");
        msg.setSubject("Esse é o assunto do email com anexo");

        Multipart multipart = new MimeMultipart();

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler("<b>Esse é o corpo do email com anexo</b>", "text / html"));
        multipart.addBodyPart(messageBodyPart, 0);

        try {

            List<String> arquivos = new ArrayList<String>();
            arquivos.add("c:\\Manual-Oracle.pdf");
            
            //multipart = anexarArquivosPorNome(multipart, arquivos);
            
            // ANEXANDO O ARQUIVO
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        msg.setContent(multipart);
        msg.saveChanges();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        msg.writeTo(outputStream);
        
        System.out.println("TAMANHO DA MENSAGEM: " + outputStream.size());

        RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

        AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);
        SendRawEmailRequest request = new SendRawEmailRequest(rawMessage);

        SendRawEmailResult resultado;

        try {

            DateFormat format = new SimpleDateFormat(
                    "HH:mm:ss");

            Date inicioProcesso = new Date();
            
            double minutos = 0;
            double segundos = 0;

            for (int i = 0; i < 1; i++) {

                String strDataInicio = format.format(new Date());
                Date inicioEnvio = new Date();

                resultado = ses.sendRawEmail(request);

                String strDataFim = format.format(new Date());
                Date fimEnvio = new Date();

                minutos = ((fimEnvio.getTime() - inicioEnvio.getTime()) / 1000) / 60;
                segundos = ((fimEnvio.getTime() - inicioEnvio.getTime()) / 1000);

                System.out.println( (i + 1) + " - PROCESSO INICIADO EM: " + strDataInicio + " FINALIZADO EM: "
                        + strDataFim + " TEMPO DE PROCESSAMENTO: "
                        + minutos + " MINUTOS E " + segundos + " SEGUNDOS");

                System.out.println((i + 1) + " - RESULTADO: " + resultado.getMessageId());
            }
            
            Date finalProcesso = new Date();

            minutos = ((finalProcesso.getTime() - inicioProcesso.getTime()) / 1000) / 60;
            segundos = ((finalProcesso.getTime() - inicioProcesso.getTime()) / 1000 % 60);

            System.out.println("TEMPO TOTAL DE PROCESSAMENTO: "
                    + minutos + " MINUTOS E " + segundos + " SEGUNDOS");

        } catch (MessageRejectedException mr) {
            System.out.println("EXCEPTION: " + mr.getMessage());

        } catch (TimerException t) {
            System.out.println("EXCEPTION: " + t.getMessage());

        } catch (Exception e) {
            System.out.println("EXCEPTION: " + e.getMessage());
        }

    }

    /*
     * 
     */
    private static Multipart anexarArquivosPorNome(Multipart multipart, List<String> listaAnexos) throws Exception {
        if (listaAnexos != null && listaAnexos.size() > 0) {

            FileInputStream fis = null;

            for (String anexo : listaAnexos) {

                try {

                    BodyPart fileBodyPart = new MimeBodyPart();

                    String caminhoArquivo = anexo;
                    File arquivo = new File(caminhoArquivo);
                    fis = new FileInputStream(arquivo);

                    //ESSE TIPO DE CODIFICACAO ABRANGE UMA GAMA MAIOR DE ARQUIVOS
                    DataSource source = new ByteArrayDataSource(fis, "application/octet-stream");
                    fileBodyPart.setDataHandler(new DataHandler(source));

                    //NOME DO ARQUIVO NO EMAIL
                    String filename = arquivo.getName();
                    fileBodyPart.setFileName(filename);
                    multipart.addBodyPart(fileBodyPart);

                } catch (Exception e) {
                    e.printStackTrace();

                } finally {

                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

            }

        }
        return multipart;
    }
}
